#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dog.h"
#include "person.h"

#include <QPushButton>
#include <QDebug>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    _p = new Person;
    _d = new Dog;

    // 使用函数指针指向
    void (Dog::*dog1)() = &Dog::hungry;
    void (Dog::*dog2)(QString) = &Dog::hungry;
    void (Person::*psn)(QString) = &Person::feed;

    // 信号的接收者可以是一个对象，也可以是多个对象
    connect(_d, dog2, _p, psn);
    connect(_d, dog2, this, &MainWindow::feedSlot);
    //// connect(ui->hungry, &QPushButton::clicked, this, &MainWindow::hungrySlot);

    // QT4的连接方式
    connect(_d, SIGNAL(hungry()), _p, SLOT(feed()));
    connect(_d, SIGNAL(hungry(QString)), _p, SLOT(feed(QString)));

    // 信号连接信号
    // connect(ui->hungry, &QPushButton::clicked, _d, &Dog::hungry);
    // connect(ui->hungry, &QPushButton::clicked, this, &MainWindow::hungrySlot);
    connect(ui->hungry, &QPushButton::clicked, this, [=](){
        emit _d->hungry();
        emit _d->hungry("狗粮");
    });

    // 实现一个关闭按钮
    connect(ui->closeBtn, &QPushButton::clicked, this, &MainWindow::close);

    MainWindow::Anonymous_func();
}

void MainWindow::Anonymous_func()
{
    // 测试匿名函数

    // 匿名函数的定义
    [](){
        qDebug() << "lambda表达式的定义句";
    };

    // 匿名函数的调用
    int a = 10, b = 20, c = 30;
    [&](){
        qDebug() << "lambda表达式的调用: ";
        qDebug() << "使用引用方式传递数据: " << "a+1: " << a++ << "b+c: " << b+c;
    }();

    // 拷贝的数据在函数体内部是只读的
    [=](int m, int n)mutable{ // mutable 修改其只读属性
        qDebug() << "lambda表达式的调用: ";
        qDebug() << "使用拷贝方式传递数据: " << "a+1: " << a++ << "b+c: " << b+c;
        qDebug() << "m+1: " << m+1 << "n+2" << n+2;
    }(1, 2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::hungrySlot()
{
    // 发射自定义信号
    // emit非必须，只是为了便于观察出是自定义信号
    emit _d->hungry();
    emit _d->hungry("狗粮");
}

void MainWindow::feedSlot()
{
    //
    qDebug() << "feedSlot的调用";
}
